package Test;

import java.util.ArrayList;

public class Test_Light_Exception {
    public static void main(String[] args) throws LightException {
        Test();
    }

    public static void Test() throws LightException {
        ArrayList<Light> l = new ArrayList<>();
        for(int i = 1; i <= 10; i ++ ){
            l.add(new Light());
        }

        boolean flag = true;

        for(Light li : l){
            try{
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

            try{
                li.turn_On();
            }catch (LightException e){
                e.printStackTrace();
                System.out.println(e.getMessage());
                li.Fix();
            }
        }

        for(Light li : l){
            try{
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

            try{
                li.turn_Off();
            }catch (LightException e){
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }

    }
}

class LightException extends Exception{
    public LightException(String msg){
        super(msg);
    }
}

class Light{
    private boolean is_On, is_Error;
    private int light_Id;
    private static int ID = 1000;

    {
        ID ++;
    }

    public Light(){
        this.light_Id = ID;
        this.is_Error = false;
    };

    public void turn_On() throws LightException {
        System.out.print(this.light_Id + "号");
        if(is_On){
            System.out.println("灯已经打开！");
        }
        else if(is_Error){
            throw new LightException("灯已损坏,需要维修！");
        }
        else{
            int random = (int) (Math.random() * 100);
            int rate = random / 50;
            if(rate == 0){
                is_Error = true;
                throw new LightException("开灯时灯损坏,请维修！");
            }
            else{
                System.out.println("打开成功！");
                is_On = true;
            }
        }
    }

    public void turn_Off() throws LightException{
        System.out.print(this.light_Id + "号");
        if(is_Error){
            throw new LightException("灯已损坏,无法关闭");
        }
        else if(is_On){
            System.out.println("关灯成功");
        }
        else{
            throw new LightException("灯已经是关闭状态");
        }
    }

    public void Fix(){
        this.is_Error = false;
        System.out.println(this.light_Id + "号灯维修成功");
    }
}
